package com.allscore.batch.test.handler;

import com.allscore.batch.test.entity.Product;

import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

/**
 * 继承FlatFileItemReader读取txt csv等
 */
@Component
// 需要参数的话，需要@StepScope注解来获取JobLauncher.run传递的参数
@StepScope
public class CsvFileReader extends FlatFileItemReader<Product> {

    // 获取JobLauncher.run时传递的参数uuid
    public CsvFileReader(@Value("#{jobParameters['uuid']}") String uuid) throws Exception {
        System.out.println("Uuid:" + uuid);
        this.setSaveState(false);// 并发必须false,不保存数据状态， 不会触发retry机制
        this.setResource(new ClassPathResource("simple.csv"));
        this.setLineMapper(new DefaultLineMapper<Product>() {
            {
                setLineTokenizer(new DelimitedLineTokenizer() {
                    {
                        setNames(new String[]{"id", "name", "quantity","description"});// csv文件按分隔符命名
                    }
                });
                setFieldSetMapper((FieldSet fieldSet) -> {
                    Product product = new Product();
                    product.setName(fieldSet.readString("name"));
                    System.out.println(fieldSet.readString("name"));
                    product.setQuantity(Integer.parseInt(fieldSet.readString("quantity")));
                    product.setDescription(fieldSet.readString("description"));
                    return product;
                });
            }
        });
        this.afterPropertiesSet();
    }

}
